import React, { useRef, useEffect } from "react";
import useLoadText from "@/utils/hooks/useLoadText";
import type { LoadedComponentProps } from "@/utils/hooks/useSequentialLoader";

const md = require("markdown-it")({
  html: true,
  linkify: true,
  typographer: true,
});

const ChatLoadMd: React.FC<LoadedComponentProps> = ({ data, onLoad }) => {
  const mdRef = useRef<HTMLDivElement>(null);
  const { showText } = useLoadText(
    data || "",
    {
      spitNum: [5, 20],
      loading: !!onLoad,
    },
    {
      onEnd: () => {
        onLoad && onLoad();
      },
    }
  );
  useEffect(() => {
    const mdStr = showText || "";
    const result = md.render(mdStr);
    if (mdRef.current) {
      mdRef.current.innerHTML = result;
    }
  }, [showText]);
  return <>{!!data && <div className="chat-load-md" ref={mdRef}></div>}</>;
};

export default ChatLoadMd;
